package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<ShopType> queryList() {
        //1.判断redis是否有
        String key = CACHE_SHOPTYPE_KEY;
        List<String> shopTypeJsonList = stringRedisTemplate.opsForList().range(key,0,-1);
        List<ShopType> shopTypeList = new ArrayList<>();
        if (CollectionUtil.isEmpty(shopTypeJsonList)){
            for (String shopTypeJsonInRedis: shopTypeJsonList) {
                shopTypeList.add(JSONUtil.toBean(shopTypeJsonInRedis, ShopType.class));
            }
            //2.有直接访问
            return shopTypeList;
        }
        //3.没有则访问数据库
        shopTypeList = this.lambdaQuery().orderByAsc(ShopType::getSort).list();
        Result.fail("该商品类型不存在");
        //4.将数据缓存到redis
        List<String> shopTypeListJson = shopTypeList.stream()
                        .map(shopType -> JSONUtil.toJsonStr(shopType))
                        .collect(Collectors.toList());
        stringRedisTemplate.opsForList().leftPushAll(key,shopTypeListJson);
        stringRedisTemplate.expire(key,CACHE_SHOPTYPE_TTL,TimeUnit.HOURS);
        //5.返回
        return shopTypeList;
    }
}
